package cn.ococci.dm.Main.Fragment;

import android.net.wifi.ScanResult;
import android.os.SystemClock;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import java.util.List;

import cn.ococci.dm.Base.BaseApp;
import cn.ococci.dm.Base.BaseFragment;
import cn.ococci.dm.Main.Const;
import cn.ococci.dm.Main.DoorBiz;
import cn.ococci.dm.Main.Model.DoorModel;
import cn.ococci.dm.Main.Model.WifiObj;
import cn.ococci.dm.Main.Tools.FilterTool;
import cn.ococci.dm.Main.Tools.LogTool;
import cn.ococci.dm.Main.Tools.SpTool;
import cn.ococci.dm.Main.Tools.StringTool;
import cn.ococci.dm.Main.Tools.ThreadTool;
import cn.ococci.dm.Main.Tools.ToastTool;
import cn.ococci.dm.Main.View.WebProgress;
import cn.ococci.dm.Network.HttpCallback;
import cn.ococci.dm.WiFi.WifiOperate;
import cn.ococci_dm.R;

/**
 * Created by cyan on 15/12/29.
 * 新增或修改门
 */
public class ModifyDoorFragment extends BaseFragment {

    public static final String TAG = ModifyDoorFragment.class.getSimpleName();

    // view
    private EditText doorNameEt;
    private Button settingBtn;
    private Button nextBridgeBtn;

    // data
    private List<ScanResult> scanResultsList;
    private DoorModel curDoor;

    private WifiOperate operate;

    @Override
    protected int getResId() {
        return R.layout.fragment_modify_door;
    }

    @Override
    protected void initView(View parent) {

        doorNameEt = (EditText) parent.findViewById(R.id.doorNameEt);
        nextBridgeBtn = (Button) parent.findViewById(R.id.nextBridgeBtn);
        settingBtn = (Button) parent.findViewById(R.id.settingBtn);
    }

    @Override
    protected void initData() {

        if (curDoor != null && !StringTool.isEmpty(curDoor.getDoorName())) {
            doorNameEt.setText(curDoor.getDoorName());
            doorNameEt.setSelection(curDoor.getDoorName().length());
            settingBtn.setText(R.string.modify_door_setting);
        }else{
            settingBtn.setText(R.string.modify_door_setting);
            settingBtn.setText(R.string.modify_door_bind_door);
        }

        operate = new WifiOperate(getActivity());
    }



    @Override
    public void initBackData() {

         if (operate.isClose()){
             operate.openWifi();
         }

        if(curDoor.getWifiName().equals(operate.returnWifiSSid())){
            operate.disconnectWifi(operate.returnCurNetworkId());
            String loginNetMac = SpTool.getString(Const.LoginParams.LOGIN_NET_NAME,"");

            final ScanResult scanResult = FilterTool.retrievalScanResult(scanResultsList,loginNetMac);
            if (scanResult != null){

                ThreadTool.runOnNewThread(new Runnable() {
                    @Override
                    public void run() {
                        handlerAutoConnected(scanResult,false);
                    }
                });
            }

        }

    }

    @Override
    protected void initListener() {

        settingBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String doorName = doorNameEt.getText().toString().trim();
                if (StringTool.isEmpty(doorName)) {
                    ToastTool.show(R.string.input_door_name);
                    return;
                }
                curDoor.setDoorName(doorName);
                setDoorInfoWithSynRoundWiFi();
            }
        });

        nextBridgeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (curDoor.getDoorId() == 0){
                    ToastTool.show(R.string.modify_fragment_need_add);
                    return;
                }
                connectingWiFi();
            }
        });

    }

    private void setDoorInfoWithSynRoundWiFi() {

        DoorBiz.setDoorInfo(false, curDoor, new HttpCallback<DoorModel>() {
            @Override
            public void onSuccess(DoorModel data) {
                ToastTool.showOnUiThread(R.string.set_success);
            }

            @Override
            public void onFailure(int code, Object msg) {
                ToastTool.showOnUiThread(R.string.set_failure);
            }
        });

        if (StringTool.hasData(scanResultsList)) {
            LogTool.log(TAG, "需要上传的周边WiFi列表：" + scanResultsList.size() + "个");
            List<WifiObj> list = DoorBiz.returnOrSaveWifiObjListData(scanResultsList, curDoor.getWifiBssid());
            DoorBiz.uploadDeviceRoundWifi(list);
        }

    }


    /**
     * 进入修改界面之前成功连接指定的WiFi
     */
    private void connectingWiFi() {

        if (operate.returnWifiSSid().equals(curDoor.getWifiName())) {

            turnTo(new BridgingDoorFragment().setDoor(curDoor));

        } else {

            if (operate.isClose()) {
                operate.isOpen();
            }

            startAutoConnectWiFi();
        }

    }

    private void startAutoConnectWiFi() {

        if (!StringTool.hasData(scanResultsList)) {
            ToastTool.show(BaseApp.findResIdDecoderString(R.string.WiFi_no_find) + (StringTool.isEmpty(curDoor.getWifiName()) ? "" : curDoor.getWifiName()));

            return;
        }

        LogTool.log(TAG,"" + curDoor.getWifiBssid());
        final ScanResult scanResult = FilterTool.retrievalScanResult(scanResultsList, curDoor.getWifiBssid());


        if (scanResult == null) {
            ToastTool.show(BaseApp.findResIdDecoderString(R.string.WiFi_no_match) + (StringTool.isEmpty(curDoor.getWifiName()) ? "" : curDoor.getWifiName()));
            return;
        }

        WebProgress.createDialog(getActivity());
        WebProgress.setLoadingStr(R.string.downloading);

        ThreadTool.runOnNewThread(new Runnable() {
            @Override
            public void run() {
                handlerAutoConnected(scanResult,true);
            }
        });


    }


    private void handlerAutoConnected(final ScanResult scanResult,final boolean hiddenDialog) {

        operate.autConnected(scanResult, new WifiOperate.ActionListener() {

            @Override
            public void onFinished(boolean success) {

                if (hiddenDialog){

                    if (success) {

                        turnTo(new BridgingDoorFragment().setDoor(curDoor).setScanResult(scanResult));
                    } else {
                        ToastTool.showOnUiThread("连接失败..请尝试手动连接");
                    }
                    WebProgress.webDismiss();
                }

            }
        });

    }


    @Override
    public String getCaption() {
        return BaseApp.findResIdDecoderString(R.string.modify_fragment_title);
    }


    public ModifyDoorFragment setDoor(DoorModel curDoor) {

        this.curDoor = curDoor;
        return this;
    }

    public void refreshListView(List<ScanResult> scanResultsList) {

        this.scanResultsList = scanResultsList;

        if (!StringTool.hasData(this.scanResultsList)){
            getMainActivity().initScanWiFi();
        }
    }


}
